<template>
  <el-dialog
    v-model="dialogVisible"
    title="选择背包物品"
    width="90%"
    :before-close="handleClose"
    class="bag-selector-dialog"
    :close-on-click-modal="false"
    :lock-scroll="false"
  >
    <div class="search-section">
      <el-input
        v-model="searchText"
        placeholder="搜索物品名称..."
        :prefix-icon="Search"
        clearable
        class="search-input"
      />
      <el-select
        v-model="selectedCategory"
        placeholder="选择分类"
        clearable
        class="category-select"
      >
        <el-option label="全部" value="" />
        <el-option
          v-for="category in categories"
          :key="category.value"
          :label="category.label"
          :value="category.value"
        />
      </el-select>
    </div>

    <div class="items-grid" v-loading="loading">
      <div
        v-for="item in filteredItems"
        :key="item.id"
        class="item-card"
        @click="handleItemClick(item)"
      >
        <div class="item-icon">
          <img
            v-if="item.type === ItemType.装备 && item.icon"
            :src="item.icon"
            :alt="item.name"
            class="item-icon-img"
          />
          <span v-else-if="item.emoji" class="item-emoji">{{ item.emoji }}</span>
          <el-icon v-else :size="32">
            <component :is="getItemIcon(item.type)" />
          </el-icon>
        </div>
        <div class="item-info">
          <div class="item-name" :style="{ background: getQualityGradient(item.quality), WebkitBackgroundClip: 'text', WebkitTextFillColor: 'transparent', backgroundClip: 'text' }">{{ item.name }}</div>
          <div class="item-count">可用: {{ getAvailableCount(item) }}</div>

        </div>
      </div>
    </div>

    <div v-if="!loading && filteredItems.length === 0" class="empty-state">
      <el-icon :size="48" color="#ccc">
        <Box />
      </el-icon>
      <p>暂无符合条件的物品</p>
    </div>

    <el-dialog v-model="showCountDialog" title="选择数量" width="80%" append-to-body>
      <div class="count-selector">
        <div class="selected-item-info">
          <img
            v-if="selectedItem?.type === ItemType.装备 && selectedItem?.icon"
            :src="selectedItem.icon"
            :alt="selectedItem.name"
            class="selected-item-icon"
          />
          <span v-else-if="selectedItem?.emoji" class="selected-item-emoji">{{
            selectedItem.emoji
          }}</span>
          <el-icon v-else :size="24">
            <component :is="getItemIcon(selectedItem?.type || 'material')" />
          </el-icon>
          <span class="item-name">{{ selectedItem?.name }}</span>
          <span class="available-count">可用: {{ selectedItem ? getAvailableCount(selectedItem) : 0 }}</span>
        </div>

        <div class="count-input-section">
          <el-input-number
            v-model="selectCount"
            :min="1"
            :max="selectedItem ? getAvailableCount(selectedItem) : 1"
            controls-position="right"
            class="count-input"
          />
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showCountDialog = false">取消</el-button>
          <el-button
            type="primary"
            @click="confirmSelection"
            style="color: white !important"
          >
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, computed, watch, onMounted } from "vue";
import {
  Search,
  Box,
  Trophy,
  Basketball,
  MagicStick,
  Star,
  Medal,
} from "@element-plus/icons-vue";
import { callApi } from "@/tool/server";
import { ResbagItem } from "@/shared/poto/bag/PtlList";
import { ItemType, quality } from "@/shared/face/enums";
import { getQualityText, getQualityGradient } from "@/shared/utils/quality";

interface Props {
  visible: boolean;
  type_id?: string; // 可选的类型过滤
  selectedItems?: Array<{id: string; count: number}>; // 已选择的道具列表
}

const props = withDefaults(defineProps<Props>(), {
  type_id: "",
  selectedItems: () => []
});

const emit = defineEmits<{
  "update:visible": [value: boolean];
  "select-item": [
    item: {
      id: string;
      name: string;
      count: number;
      icon?: string;
      emoji?: string;
      type: string;
    }
  ];
}>();

const dialogVisible = ref(false);
const searchText = ref("");
const selectedCategory = ref("");
const showCountDialog = ref(false);
const selectCount = ref(1);
const selectedItem = ref<ResbagItem | null>(null);
const loading = ref(false);
const bagItems = ref<ResbagItem[]>([]);

// 计算道具的实际可用数量（减去已选择的数量）
const getAvailableCount = (item: ResbagItem) => {
  const selectedItem = props.selectedItems.find(selected => selected.id === item.id);
  const selectedCount = selectedItem ? selectedItem.count : 0;
  return Math.max(0, item.cont - selectedCount);
};

// 获取过滤后的道具列表，排除已无可用数量的道具
const filteredItems = computed(() => {
  let items = bagItems.value.filter(item => getAvailableCount(item) > 0);

  if (selectedCategory.value) {
    items = items.filter((item) => item.type === selectedCategory.value);
  }

  if (searchText.value) {
    items = items.filter((item) =>
      item.name.toLowerCase().includes(searchText.value.toLowerCase())
    );
  }

  return items;
});

watch(
  () => props.visible,
  (newVal) => {
    dialogVisible.value = newVal;
    if (newVal) {
      loadBagItems();
    }
  }
);

watch(dialogVisible, (newVal) => {
  if (!newVal) {
    emit("update:visible", false);
  }
});

// 加载背包数据
const loadBagItems = async () => {
  loading.value = true;
  try {
    const res = await callApi("bag/List", { type_id: props.type_id });
    if (res && res.list) {
      bagItems.value = res.list;
    } else {
      bagItems.value = [];
    }
  } catch (error) {
    console.error("加载背包数据失败:", error);
    bagItems.value = [];
  } finally {
    loading.value = false;
  }
};

const categories = [
  { label: "装备", value: ItemType.装备 },
  { label: "道具", value: ItemType.道具 },
  { label: "技能书", value: ItemType.技能书 },
  { label: "宠物蛋", value: ItemType.宠物蛋 },
  { label: "血统卷轴", value: ItemType.血统卷轴 },
  { label: "盲盒", value: ItemType.盲盒 },
  { label: "形象卡", value: ItemType.形象卡 },
];

const getItemIcon = (type: string) => {
  const iconMap = {
    weapon: Trophy,
    armor: Basketball,
    potion: MagicStick,
    gem: Star,
    material: Box,
    rare: Medal,
  };
  return iconMap[type as keyof typeof iconMap] || Box;
};



const selectItem = (item: ResbagItem) => {
  const availableCount = getAvailableCount(item);
  if (availableCount <= 0) {
    return; // 如果没有可用数量，不允许选择
  }
  selectedItem.value = item;
  selectCount.value = Math.min(1, availableCount);
  showCountDialog.value = true;
};

const handleItemClick = (item: ResbagItem) => {
  selectItem(item);
};

const confirmSelection = () => {
  if (selectedItem.value && selectCount.value > 0) {
    emit("select-item", {
      id: selectedItem.value.id,
      name: selectedItem.value.name,
      count: selectCount.value,
      icon:
        selectedItem.value.type === ItemType.装备 ? selectedItem.value.icon : undefined,
      emoji:
        selectedItem.value.type !== ItemType.装备 ? selectedItem.value.emoji : undefined,
      type: selectedItem.value.type,
    });

    showCountDialog.value = false;
    dialogVisible.value = false;
  }
};

const handleClose = () => {
  dialogVisible.value = false;
};
</script>

<style lang="scss" scoped>
.bag-selector-dialog {
  :deep(.el-dialog__body) {
    padding: 20px;
    max-height: 70vh;
    overflow-y: auto;
    -webkit-overflow-scrolling: touch;

    @media (max-width: 768px) {
      padding: 15px;
      max-height: 75vh;
    }
  }

  .search-section {
    display: flex;
    gap: 10px;
    margin-bottom: 20px;

    .search-input {
      flex: 1;
    }

    .category-select {
      width: 120px;
    }

    @media (max-width: 768px) {
      flex-direction: column;
      gap: 8px;

      .category-select {
        width: 100%;
      }
    }
  }

  .items-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
    gap: 12px;
    max-height: 400px;
    overflow-y: auto;
    overflow-x: hidden;
    -webkit-overflow-scrolling: touch;
    touch-action: pan-y;

    @media (max-width: 768px) {
      grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
      max-height: 50vh;
      gap: 8px;
    }
  }

  .item-card {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 15px;
    border: 2px solid #e0e0e0;
    border-radius: 8px;
    background: rgba(255, 255, 255, 0.8);
    cursor: pointer;
    transition: all 0.3s ease;
    touch-action: manipulation;

    &:hover {
      border-color: #409eff;
      box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15);
      transform: translateY(-2px);
    }

    &:active {
      transform: scale(0.98);
    }

    @media (max-width: 768px) {
      padding: 10px;

      &:hover {
        transform: none;
      }
    }

    .item-icon {
      margin-bottom: 8px;
      color: #409eff;
      display: flex;
      align-items: center;
      justify-content: center;
      width: 32px;
      height: 32px;

      .item-icon-img {
        width: 32px;
        height: 32px;
        border-radius: 4px;
        object-fit: cover;
      }

      .item-emoji {
        font-size: 32px;
        line-height: 32px;
        width: 32px;
        height: 32px;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }

    .item-info {
      text-align: center;
      width: 100%;

      .item-name {
        font-size: 14px;
        font-weight: 500;
        margin-bottom: 4px;
        word-break: break-all;
      }

      .item-count {
        font-size: 12px;
        color: #666;
        margin-bottom: 4px;
      }

      .item-rarity {
        font-size: 11px;
        padding: 2px 6px;
        border-radius: 4px;
        font-weight: 500;
        color: white;
        text-shadow: -1px -1px 0 rgba(0, 0, 0, 0.8), 1px -1px 0 rgba(0, 0, 0, 0.8),
          -1px 1px 0 rgba(0, 0, 0, 0.8), 1px 1px 0 rgba(0, 0, 0, 0.8);
      }
    }
  }

  .empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 60px 20px;
    color: #999;

    p {
      margin-top: 16px;
      font-size: 14px;
    }
  }
}

.count-selector {
  .selected-item-info {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 20px;
    padding: 15px;
    background: #f8f9fa;
    border-radius: 8px;

    .selected-item-icon {
      width: 24px;
      height: 24px;
      border-radius: 4px;
      object-fit: cover;
    }

    .selected-item-emoji {
      font-size: 24px;
      line-height: 24px;
      width: 24px;
      height: 24px;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .item-name {
      font-weight: 500;
      flex: 1;
    }

    .available-count {
      font-size: 12px;
      color: #666;
    }
  }

  .count-input-section {
    display: flex;
    justify-content: center;

    .count-input {
      width: 150px;
    }
  }
}
</style>
